//
//  NSString+JSON.m
//  NSURLSession封装
//
//  Created by 周成龙 on 16/11/1.
//  Copyright © 2016年 ZCL. All rights reserved.
//

#import "NSString+JSON.h"

@implementation NSString (JSON)

+ (NSString *)JSONStringWithDiction:(id)infoDict {
    if (!infoDict) {
        return nil;
    }
    NSError *error = nil;
    NSData *data = [NSJSONSerialization dataWithJSONObject:infoDict options:NSJSONWritingPrettyPrinted error:&error];
    if (error) {
        return nil;
    }
    NSString *jsonstring = @"";
    if (!jsonstring) {
        return nil;
    }
    jsonstring = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    //去除掉首尾的空白字符和换行字符
    jsonstring = [jsonstring stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    // 将 \n 替换掉
    jsonstring = [jsonstring stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    return jsonstring;
}

+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (!jsonString) {
        return nil;
    }
    NSError *error = nil;
    NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
    if (error) {
        return nil;
    }
    return dict;
}

@end
